// app.ts
import { userAPI, qrLoginAPI } from './utils/api';

interface UserInfo {
  nickname: string
  avatar: string
  level: string
  gameId: string
  qq_number: string
  registerTime: string
  total_consumption_amount?: number
  role?: string
}

// 等级系统配置
const levelConfig = [
  { level: 0, name: '时界星穹の鼠王', minAmount: 0, info: '等级：0  消费金额满0' },
  { level: 1, name: '苍穹霜冕の白银之翼', minAmount: 88, info: '等级：1  消费金额满88' },
  { level: 2, name: '夜魇终焉の漆黑之翼', minAmount: 888, info: '等级：2  消费金额满888' },
  { level: 3, name: '寂灭黑皇の琳达黑暗化身', minAmount: 5888, info: '等级：3  消费金额满5888' },
  { level: 4, name: '时序圣冠の琳达', minAmount: 11888, info: '等级：4  消费金额满11888' },
  { level: 5, name: '星糖冕冠の多拉姆糖', minAmount: 38888, info: '等级：5  消费金额满38888' },
  { level: 6, name: '时界星穹主の阿尔杰斯', minAmount: 88888, info: '等级：6  消费金额满88888' },
  { level: 99, name: '拍卖师', minAmount: Number.MAX_SAFE_INTEGER, info: '等级：7  拍卖师/管理员专属等级' }
]

// 根据消费金额和角色获取用户等级
const getUserLevel = (consumptionAmount: number | null | undefined, role?: string) => {
  // 如果是拍卖师或管理员，直接返回最高等级
  if (role === 'auctioneer' || role === 'admin') {
    return levelConfig[levelConfig.length - 1] // 返回最高等级（拍卖师）
  }

  if (consumptionAmount === null || consumptionAmount === undefined || consumptionAmount < 0) {
    return levelConfig[0] // 默认返回等级0
  }

  // 从高到低查找匹配的等级
  for (let i = levelConfig.length - 1; i >= 0; i--) {
    if (consumptionAmount >= levelConfig[i].minAmount) {
      return levelConfig[i]
    }
  }

  return levelConfig[0] // 默认返回等级0
}

App<IAppOption>({
  globalData: {
    userInfo: {} as UserInfo,
    userLevel: levelConfig[0],
    profileVisible: false,
    isLoggedIn: false,
    currentScene: ''
  },

  onLaunch(options) {
    console.log("小程序启动", options);

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 获取scene参数
    const scene = options.query.scene || '';
    this.globalData.currentScene = scene;
    console.log('获取到scene参数:', scene);

    // 处理登录逻辑
    this.handleGlobalLogin(scene);
  },

  // 全局登录处理
  async handleGlobalLogin(scene: string) {
    await this.checkGlobalProfileVisibility();

    try {
    

      // 如果有scene参数，进行扫码登录
      if (scene) {
        this.callLoginAPIFun(scene)
      } else {
        // 没有scene参数，检查是否有已保存的token
        const token = wx.getStorageSync('accessToken');
        if (token) {
          this.globalData.isLoggedIn = true;
          await this.fetchGlobalUserInfo();
        }else{
          this.callLoginAPIFun('')
        }
      }
      
    } catch (error: any) {
      wx.hideLoading();
      console.error('全局登录失败:', error);
      
      // 检查是否是403错误
      if (error.statusCode === 403) {
        console.log('检测到403错误，需要调用miniprogramLogin');
        this.showGlobalLoginError('登录验证失败，请重试');
      } else {
        this.showGlobalLoginError('登录失败，请重试');
      }
    }
  },
  async callLoginAPIFun(scene){
  wx.showLoading({ title: '登录中...' });
        
  // 1. 获取小程序登录凭证
  const { code } = await this.wxLogin();
  console.log('获取到登录凭证:', code);
  
  // 2. 调用登录接口
  const result = await this.callLoginAPI(scene, code, {});
  
  if (result.success) {
    // 3. 保存token到本地存储
    const { tokens } = result;
    wx.setStorageSync('accessToken', tokens.access_token);
    console.log('Token已保存到本地存储');
    
    // 4. 设置登录状态
    this.globalData.isLoggedIn = true;
    
    // 5. 获取用户信息
    await this.fetchGlobalUserInfo();
    
    // 6. 显示登录成功
    this.showGlobalLoginSuccess(result);
  } else {
    wx.hideLoading();
    this.showGlobalLoginError(result.message || '登录失败');
  }
},
  // 微信登录
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      });
    });
  },

  // 调用登录API
  callLoginAPI(scene: string, code: string, userInfo: any) {
    return qrLoginAPI.miniprogramLogin(scene, code, userInfo);
  },

  // 全局获取用户信息
  async fetchGlobalUserInfo() {
    try {
      console.log('全局获取用户信息');
      const response = await userAPI.getUserInfo();
      console.log('获取用户信息成功:', response);
      
      if (response) {
        const userInfo = {
          ...this.globalData.userInfo,
          ...response
        };
        
        this.globalData.userInfo = userInfo;
        
        // 更新用户等级
        this.updateGlobalUserLevel(userInfo.total_consumption_amount, userInfo.role);
        
        // 将用户信息保存到本地存储
        wx.setStorageSync('userInfo', response);
      }
    } catch (error: any) {
      console.error('全局获取用户信息失败:', error);
      
      if (error.statusCode === 403) {
        console.log('获取用户信息时检测到403错误');
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  },

  // 更新全局用户等级
  updateGlobalUserLevel(consumptionAmount: number | null | undefined, role?: string) {
    const userLevel = getUserLevel(consumptionAmount, role);
    console.log('全局用户等级:', userLevel, '角色:', role);
    
    this.globalData.userLevel = userLevel;
  },

  // 检查全局个人资料显示隐藏状态
  async checkGlobalProfileVisibility() {
    try {
      const response = await userAPI.getProfileVisibility();
      console.log('全局个人资料显示隐藏状态:', response);
      if (response) {
        this.globalData.profileVisible = response.show_profile;
      }
    } catch (error: any) {
      console.error('获取全局个人资料显示隐藏状态失败:', error);
      // 如果获取失败，默认显示
      this.globalData.profileVisible = false;
    }
  },

  // 显示全局登录成功
  showGlobalLoginSuccess(data: any) {
    const { user } = data;
    
    // wx.showToast({
    //   title: user.is_new_user ? '注册成功！' : '登录成功！',
    //   icon: 'success'
    // });
    
    // 隐藏加载状态
    wx.hideLoading();
  },

  // 显示全局登录错误
  showGlobalLoginError(message: string) {
    wx.showToast({
      title: message,
      icon: 'error',
      duration: 3000
    });
  }
})